package com.ybwh.springboot2.satoken.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.ybwh.springboot2.common.BusinessException;
import com.ybwh.springboot2.common.meta.UserInfo;
import com.ybwh.springboot2.satoken.dao.SysUserMapper;
import com.ybwh.springboot2.satoken.model.entity.SysUser;
import com.ybwh.springboot2.satoken.service.SysUserService;
import com.ybwh.springboot2.util.PasswordUtils;
import com.ybwh.springboot2.util.SatokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户服务接口实现类
 * </p>
 *
 * @author youbeiwuhuan
 * @version V1.0
 * @since 2023-04-21 16:43:39
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;


    @Override
    public PageInfo<SysUser> queryByPage(SysUser param, int pageNum, int pageSize) {
        Preconditions.checkArgument(pageNum > 0);
        Preconditions.checkArgument(pageSize > 0);

        Page<SysUser> page = sysUserMapper.selectByPage(param, pageNum, pageSize);

        return new PageInfo<>(page);
    }

    @Override
    public String login(String username, String password) {
        SysUser user = sysUserMapper.selectByUsername(username);
        if (null == user) {
            throw new BusinessException("账号密码不正确");
        }

        if (PasswordUtils.checkPassword(password, user.getPassword())) {
            throw new BusinessException("账号密码不正确");
        }

        UserInfo userInfo = UserInfo.builder().id(user.getId())
                .account(user.getUserName())
                .nikeName(user.getNickName())
                .mobile(user.getMobile())
                .email(user.getEmail()).build();


        Map<String, Object> dataMap = new HashMap<>();
        return SatokenUtils.login(userInfo, dataMap);
    }


}
